package com.bwie.gateway.filters;

import com.bwie.common.constants.JwtConstants;
import com.bwie.common.constants.TokenConstants;
import com.bwie.common.utils.JwtUtils;
import com.bwie.common.utils.StringUtils;
import com.bwie.gateway.config.IgnoreWhiteConfig;
import com.bwie.gateway.utils.GatewayUtils;
import io.jsonwebtoken.Jwt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.*;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;

/**
 * @ClassName:
 * @Description: 鉴权过滤器
 * @Author: zhuwenqiang
 * @Date: 2023/9/14
 */
@Component
public class AuthFilter implements GlobalFilter, Ordered {

    @Autowired
    private IgnoreWhiteConfig ignoreWhitesConfig;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    /**
     * 过滤方法 拦截请求 验证请求头中的 token
     * @param exchange 请求的上下文对象
     * @param chain    网关过滤器链
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 判断当前的请求是否需要拦截  【白名单请求  不拦截的请求  通过配置配置的 】
        // 1、获取系统配置好的白名单请求
        List<String> whites = ignoreWhitesConfig.getWhites();
        // 获取当前请求的 URI
        ServerHttpRequest exchangeRequest = exchange.getRequest();
        String path = exchangeRequest.getURI().getPath();
        if (StringUtils.matches(path, whites)) {
            // 白名单请求 放行
            return chain.filter(exchange);
        }
        // 先获取 token
        String token = exchangeRequest.getHeaders().getFirst(TokenConstants.TOKEN);
        // 非空验证
        if (StringUtils.isBlank(token)) {
            return GatewayUtils.errorResponse(exchange, "token不能为空", HttpStatus.UNAUTHORIZED);
        }
        // 合法性
        try {
            JwtUtils.parseToken(token);
        } catch (Exception e) {
            return GatewayUtils.errorResponse(exchange, "token不合法！");
        }
        // 有效性
        // 获取 userKey
        String userKey = JwtUtils.getUserKey(token);
        if (!redisTemplate.hasKey(TokenConstants.LOGIN_TOKEN_KEY + userKey)) {
            return GatewayUtils.errorResponse(exchange, "token失效");
        }
        // 放行
        return chain.filter(exchange);
    }

    /**
     * 规定过滤器执行顺序
     * @return 数字 数字的值越小 优先级越高
     */
    @Override
    public int getOrder() {
        return 0;
    }
}
